﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Channels;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using DaInterFace;

namespace DataApplication
{
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
    public class MobileApi : IMobileApi
    {
        private const String  PublicKey = "<RSAKeyValue><Modulus>kky++sW4qqlZudQ1jWzjef41jviR2AV63JxeExiKi0ZziL9pUbG+F9X32w+bZ6OIw/mm4RYDwDNRELIun70izPUhyrUnsprKEgRVC3DYfKE1Okjnmj6WV07Inxe82TYWRDAEdsSZ+dr7JSmQhgEB1JZ0IJw0ajXM12vxzh13gOk=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
        private const String PrivateKey = "<RSAKeyValue><Modulus>kky++sW4qqlZudQ1jWzjef41jviR2AV63JxeExiKi0ZziL9pUbG+F9X32w+bZ6OIw/mm4RYDwDNRELIun70izPUhyrUnsprKEgRVC3DYfKE1Okjnmj6WV07Inxe82TYWRDAEdsSZ+dr7JSmQhgEB1JZ0IJw0ajXM12vxzh13gOk=</Modulus><Exponent>AQAB</Exponent><P>yw8eafJmDEMjaOltZQv/tZOqyaV9wfrRSw9UXb28wCvqb0iUs0ZpDPrSztz0CUKgaXnpOHd+4G8Ur9qiJg7sDQ==</P><Q>uHFP/NCaUdMRMMNDUeitb5tErfDYBvtqiuzv0GQ3IwM6uMtr6HFwkEzIQhOL0GcSHWNvExhc29L2fj4dtQdFTQ==</Q><DP>iyLe6iWn+vr+BmL8DGL+YgK+4dC9rO8Z/d6RJnJeJSdySbJoAbdbQAOV8xy/MqEunVdlkMWAcHRsrlqXBJDw+Q==</DP><DQ>k/9AaqFMIroVQiZ8Xz4v5K0XN+dYwIl+3UjvySyQ3YRa2ytHQ/W6l980lWivuKLr8y71UsIqyK0H4xaeqcLSxQ==</DQ><InverseQ>TWf+/tOAF1Ejt57O4/0lPbiEiPlKGa4I1ZetyfVmPgd71jLOJgH8x5otnucGil4QwQ5Ipl1hEs/JHAauKrRqeA==</InverseQ><D>Mx4zwMWjP6ZKnp6iU5cPaInFRv5dX0CS7FCKolt51S45ojdXYl8bj5KItvceErlWSTuK7qzVhKupkI7hsZjRdopumiUeFBUXt67TwlefXNj2DeBTZ/s9hTvRE5b6M1SjQvlwMKkaUa+dcwwlpeDLb6NIyRc8WDfponGdzNiuzbE=</D></RSAKeyValue>";
        
        public static IMobile DaMobile;

        private static Dictionary<string, MobileUser> UserDictionary = new Dictionary<string, MobileUser>();
        private static Dictionary<string, MobileUser> BlackList = new Dictionary<string, MobileUser>();

        public string GetAccounts()
        {
            //DaMobile.Message(MessageType.Note, "获取账套信息");
            return JsonXMLSerial.ObjectClassToJson(DaMobile.DaData.GetAccounts());
        }

        public string Login(string parameter)
        {
            LoginResult cr = new LoginResult();
            //获取消息发送的远程终结点IP和端口
            RemoteEndpointMessageProperty endpoint = OperationContext.Current.IncomingMessageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
            
            try
            {
                LoginParameters p = (LoginParameters)JsonXMLSerial.JsonToObjectClass(parameter, typeof(LoginParameters));

                SqlParameter[] sps = new SqlParameter[1];
                sps[0] = new SqlParameter("@UserName", SqlDbType.NChar, 50);
                sps[0].Value = p.UserName;

                String sql = "SELECT FText Pswd,FCheckBox1 IMEI FROM KEW_SalesGuests WHERE FCheckBox=1 AND FBillNo=@UserName\r\nSELECT FText2 IMEI FROM KEW_SalesGuestsIMEI WHERE FID =(SELECT FID FROM KEW_SalesGuests WHERE FCheckBox=1 AND FBillNo=@UserName)";
                Recordset rs = DaMobile.DaData.ExeProcedure(p.AccountID, sql, sps);

                if (rs.Enable)
                {
                    if (rs.Data.Tables[0].Rows.Count != 1)
                    {
                        cr.Enable = false;
                        cr.Message = "用户名错误";
                    }
                    else if (rs.Data.Tables[0].Rows[0]["Pswd"].ToString() != p.PassWord)
                    {
                        cr.Enable = false;
                        cr.Message = "密码错误";
                    }
                    else
                    {
                        Boolean isIMEI = false;
                        if (Common.CBool(rs.Data.Tables[0].Rows[0]["IMEI"].ToString()))
                        {
                            foreach (DataRow row in rs.Data.Tables[1].Rows)
                            {
                                if (row["IMEI"].ToString() == p.IMEI)
                                {
                                    isIMEI = true;
                                }
                            }
                        }
                        else
                        {
                            isIMEI = true;
                        }
                        if (isIMEI)
                        {
                            UserDictionary.Remove(p.UserName);
                            MobileUser mu = new MobileUser();
                            mu.Key = Guid.NewGuid().ToString();
                            mu.IMEI = p.IMEI;
                            mu.AccountID = p.AccountID;
                            mu.UserName = p.UserName;
                            mu.LoginTime = DateTime.Now;
                            mu.VisitTime = DateTime.Now;
                            UserDictionary.Add(mu.UserName, mu);

                            cr.Enable = true;
                            cr.Key = mu.Key;

                            //DaMobile.Message(MessageType.Note, String.Format("用户[{0}]登录成功，IMEI：{1},IP:{2}", p.UserName, p.IMEI, endpoint.Address));
                            DaMobile.Message(MessageType.Note, String.Format("用户[{0}]登录成功，IMEI：{1},IP:{2}", p.UserName, p.IMEI, OperationContext.Current.SessionId)); 
                        }
                        else
                        {
                            cr.Enable = false;
                            cr.Message = "此设备不允许登录！";
                            DaMobile.Message(MessageType.Warning, String.Format("用户[{0}]登录的设备不在允许的范围内，IMEI：{1},IP:{2}", p.UserName, p.IMEI, endpoint.Address));
                        }
                    }

                }
                else
                {
                    cr.Enable = false;
                    cr.Message = rs.Message;
                }
            }
            catch (Exception ex)
            {
                cr.Enable = false;
                cr.Message = ex.Message;
            }

            return JsonXMLSerial.ObjectClassToJson(cr);
        }

        private int CheckUser(MobileClient mc)
        {
            if (UserDictionary.ContainsKey(mc.UserName))
            {
                if (UserDictionary[mc.UserName].IMEI == mc.IMEI && UserDictionary[mc.UserName].Key == mc.Key)
                {
                    UserDictionary[mc.UserName].VisitTime = DateTime.Now;
                    return 0;
                }
                else
                {
                    return 1;
                }
            }
            else
            {
                return 2;
            }
        }

        private ClientUser ConvertUserClass(MobileUser mu)
        {
            ClientUser cu = new ClientUser();
            cu.AccountID = mu.AccountID;
            cu.UserName = mu.UserName;
            cu.LoginTime = mu.LoginTime;
            cu.VisitTime = mu.VisitTime;

            return cu;
        }

        public string Code(string parameter)
        {
            CodeResult cr = new CodeResult();
            MobileParameter mp = (MobileParameter)JsonXMLSerial.JsonToObjectClass(parameter, typeof(MobileParameter));
            String crstring = string.Empty;
            String[] splitCode = mp.CodeName.Split('.');

            if (splitCode.Length != 2)
            {
                cr.Enable = false;
                cr.Message = "错误的功能代码！";

                return JsonXMLSerial.ObjectClassToJson(cr);
            }
            String file = splitCode[0];
            String code = splitCode[1];


            try
            {

                int crst = CheckUser(mp.Client);

                switch (crst)
                {
                    case 0:

                        MobileHandler handler = new MobileHandler();
                        handler.Mobile = DaMobile;
                        handler.User = ConvertUserClass(UserDictionary[mp.Client.UserName]);

                        switch (code)
                        {
                            case "0": break;
                            default:
                                try
                                {
                                    Assembly ass = Assembly.Load(file);  //加载dll文件
                                    Type tp = ass.GetType(file + "." + code);  //获取类名，必须 命名空间+类名
                                    IMobileChild temp = (IMobileChild)Activator.CreateInstance(tp);  //建立实例
                                    cr.JsonObj = temp.Code(handler, mp.Parameters);
                                    cr.Enable = true;
                                    cr.Result = 0;
                                }
                                catch (Exception ex)
                                {
                                    cr.Enable = false;
                                    cr.Result = 4;
                                    cr.Message = ex.Message;
                                }
                                break;
                        }

                        break;
                    case 1:
                        cr.Enable = false;
                        cr.Result = 1;
                        cr.Message = "无效的登录信息，请重复登录。";
                        break;
                    case 2:
                        cr.Enable = false;
                        cr.Result = 2;
                        cr.Message = "请先登录。";
                        break;
                }
            }
            catch (Exception ex)
            {
                cr.Enable = false;
                cr.Result = 5;
                cr.Message = ex.Message;
            }

            try
            {
                crstring = JsonXMLSerial.ObjectClassToJson(cr);
            }
            catch (Exception ex)
            {
                cr.Enable = false;
                cr.Result = 6;
                cr.Message = ex.Message;
            }

            return crstring;
        }
    }
}
